//
//  LockView.m
//  LockViewDemo
//
//  Created by jianyong.wang on 2017/12/4.
//  Copyright © 2017年 jianyong.wang. All rights reserved.
//

#import "LockView.h"
@interface LockView()
@property (nonatomic,strong) NSMutableArray * selectedArray;//当前选中按钮数组
@property (nonatomic,strong) NSMutableArray * errorArray;//错误按钮数组
@property (nonatomic,assign) CGPoint currentPoint;//当前触摸点位置
@property (nonatomic,assign) BOOL finished;//是否完成
@property (nonatomic,assign) ResultPwdType resultPwd;//测试密码状态
@property (nonatomic,assign) SetPwdType setPwd;//设置密码状态
@end
@implementation LockView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

-(void)addPanGesture
{
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGes:)];
    [self addGestureRecognizer:pan];
}
//开始绘制
-(void)panGes:(UIPanGestureRecognizer *)pan
{
    //开始滑动手势
    if(pan.state == UIGestureRecognizerStateBegan){
        //先将errorBtns所有按钮图片置为默认图片
        for (UIButton * btn in self.errorArray) {
            [btn setImage:[UIImage imageNamed:@"sign_img_circle_n"] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:@"sign_img_circle_s"] forState:UIControlStateSelected];
        }
        [self.errorArray removeAllObjects];
        //将当前选中的状态反转
        for (UIButton * btn  in self.selectedArray) {
           btn.selected = false;
        }
        [self.selectedArray removeAllObjects];
    }
    //获取当前触摸点位置
    self.currentPoint = [pan locationInView:self];
    //当触摸点在按钮范围内，将按钮置为选中状态
    for (UIButton * btn  in self.subviews) {
        if (CGRectContainsPoint(btn.frame, self.currentPoint)) {
            if (!btn.selected) {
                //更改按钮状态
                btn.selected = true;
                //添加进选中按钮数组中
                [self.selectedArray addObject:btn];
            }
        }
    }
    //绘制线条
    [self setNeedsDisplay];
    //结束手势
    if (pan.state == UIGestureRecognizerStateEnded) {
        self.finished = true;
    }
}
#pragma mark - draw
-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    if (self.selectedArray.count == 0) {
        return;
    }
    //将所有选中按钮连线
    UIBezierPath * path = [UIBezierPath bezierPath];
    for (int i = 0; i<self.selectedArray.count; i++) {
        UIButton * btn = self.selectedArray[i];
        if (i == 0) {
            [path moveToPoint:btn.center];
        }else [path addLineToPoint:btn.center];
    }
    //判断是否已经结束
    if (self.finished) {
        if(self.delegate && [self.delegate respondsToSelector:@selector(lockView:drawFinished:)])
        {
            [self.delegate lockView:self drawFinished:[self FetchRealPwd]];
        }
        if (self.isTest) {//测试
            //如果选中的点小于4个,设置绘制颜色为透明，否则为绿色
            if (self.resultPwd == ResultPwdTypeNoEnough) {
                [[UIColor clearColor]set];
            }else  if (self.resultPwd == ResultPwdTypeTrue)  {
                //正确
                [[UIColor clearColor] set];
            }else if (self.resultPwd == ResultPwdTypeFalse){
                //错误
                [[UIColor redColor] set];
                for (int i = 0; i < self.errorArray.count; i++) {
                    UIButton *btn =  [self.errorArray objectAtIndex:i];
                    [btn setImage:[UIImage imageNamed:@"sign_img_circle_p"] forState:UIControlStateSelected];//此处只需要设置选中状态即可，因为当前绘制的按钮即为选中状态下的
                }
            }
        }else{//设置密码
            //如果选中的点小于4个,设置绘制颜色为透明，否则为绿色
            if (self.setPwd == SetPwdTypeNoEnough) {
                [[UIColor clearColor]set];
            }else [[UIColor colorWithRed:94/255.0 green:195/255.0 blue:49/255.0 alpha:0.8] set];
        }
    }else{//未完成，则继续添加贝塞尔直线
        [path addLineToPoint:self.currentPoint];
        [[UIColor colorWithRed:94/255.0 green:195/255.0 blue:49/255.0 alpha:0.8] set];
    }
    path.lineWidth = 1;
    path.lineJoinStyle = kCGLineCapRound;
    path.lineCapStyle = kCGLineCapRound;
    [path stroke];
}
#pragma mark - Other

/**
 获取当前绘制的手势对应的数字密码

 @return <#return value description#>
 */
- (NSMutableString *)FetchRealPwd {
    //创建可变字符串
    NSMutableString *result = [NSMutableString string];
    for (UIButton *btn in self.selectedArray) {
        [result appendFormat:@"%ld", btn.tag];
    }
    return result;
}

-(void)checkSetPwd:(SetPwdType)type
{
    self.setPwd = type;
    switch (type) {
        case SetPwdTypeTrue:
            break;
        case SetPwdTypeNoEnough:
            [self clearLockView];//如果设置密码错误，清空界面
            break;
    }
}
-(void)checkResultPwd:(ResultPwdType)type
{
    self.resultPwd = type;
    switch (type) {
        case ResultPwdTypeTrue:
            [self clearLockView];
            break;
        case ResultPwdTypeFalse://若密码错误，那么直接将选中按钮职位其他图片
            self.errorArray = [self.selectedArray mutableCopy];
            break;
        case ResultPwdTypeNoEnough:
            [self clearLockView];
            break;
        case ResultPwdTypeClear:
            [self clearLockView];
            break;
    }
}

/**
 清空状态
 */
-(void)clearLockView
{
    self.finished = NO;
    //遍历所有选中的按钮
    for (UIButton *btn in self.selectedArray) {
        btn.selected = NO;
    }
    [self.selectedArray removeAllObjects];
    //遍历所有错误的按钮
    for (UIButton * btn in self.errorArray) {
        [btn setImage:[UIImage imageNamed:@"sign_img_circle_n"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"sign_img_circle_s"] forState:UIControlStateSelected];
    }
    [self.errorArray removeAllObjects];
    //重绘
    [self setNeedsDisplay];
}
#pragma mark - lazy
-(NSMutableArray *)selectedArray
{
    if (_selectedArray == nil) {
        _selectedArray = [NSMutableArray array];
    }
    return _selectedArray;
}
-(NSMutableArray *)errorArray
{
    if (_errorArray == nil) {
        _errorArray = [NSMutableArray array];
    }
    return _errorArray;
}
@end
